<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            let arr = [1, 2, 3, 4, 5];
            // let arr1 = arr.flatMap((item) => [item * 2]);
            // console.log(arr1); // [2, 4, 6, 8, 10]
            // console.log(arr); // [1, 2, 3, 4, 5] 原数组没有发生改变
            // let arr2 = arr.flatMap((item) => [[item * 2]]);
            // console.log(arr2); // 只能拍平一层 [[2], [4], [6], [8], [10]];
            // console.log(arr); // [1, 2, 3, 4, 5]

            Array.prototype.myFlatMap = function (callback, thisArg) {
                let newArr = [];
                for (let i = 0; i < this.length; i++) {
                    let res = callback.call(thisArg, arr[i], i, arr);
                    if (Array.isArray(res)) {
                        newArr.push(...res);
                    } else {
                        newArr.push(res);
                    }
                }
                return newArr;
            };
            let arr1 = arr.flatMap((item) => [item * 2]);
            console.log(arr1); // [2, 4, 6, 8, 10]
            let arr2 = arr.myFlatMap((item) => [[item * 2]]);
            console.log(arr2); // 只能拍平一层 [[2], [4], [6], [8], [10]];
        </script>
    </body>
</html>
